<template>
  <div class="panel-item">
    <div class="panel-title">
      上传图片 - 图片用作参照时不会打印，仅用于辅助调整打印位置
    </div>
    <div class="panel-content">
      <div class="upload-options">
        <div class="radio-group">
          <el-radio v-model="uploadType" label="network">网络图片</el-radio>
          <el-radio v-model="uploadType" label="local">上传本地图片</el-radio>
        </div>
        <div class="upload-actions">
          <template v-if="uploadType === 'network'">
            <el-input v-model="localNetworkUrl" size="small" placeholder="输入图片URL" style="width: 100%" :disabled="hasBackground"></el-input>
            <div class="button-group">
              <el-button 
                v-if="!hasBackground" 
                size="small" 
                type="success" 
                @click="handleNetworkImage">添加为背景图</el-button>
              <el-button 
                v-if="hasBackground" 
                size="small" 
                type="danger" 
                @click.stop="removeBackground">删除背景图</el-button>
            </div>
          </template>
          <template v-else>
            <el-upload
              class="uploader-container"
              action=""
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleFileChange"
              :disabled="hasBackground"
              :accept="'image/jpeg,image/png,image/gif,image/webp,image/bmp'"
              :before-upload="() => false"
            >
              <template #trigger>
                <div class="upload-trigger">
                  <el-button 
                    v-if="!hasBackground" 
                    size="small" 
                    type="success">添加为背景图</el-button>
                  <div v-if="!hasBackground" class="upload-tip">点击按钮选择图片文件</div>
                </div>
              </template>
            </el-upload>
            <div class="button-group" v-if="hasBackground">
              <el-button 
                size="small" 
                type="danger" 
                @click.stop="removeBackground">删除背景图</el-button>
            </div>
          </template>
        </div>
        
        <!-- 背景图片编辑控制和透明度设置 -->
        <div v-if="hasBackground" class="background-controls">
          <!-- 编辑模式切换按钮 -->
          <div class="edit-mode-toggle">
            <el-switch
              v-model="editModeActive"
              active-text="编辑模式"
              inactive-text="锁定模式"
              @change="toggleEditMode"
            ></el-switch>
            <div class="mode-tip">{{ editModeActive ? '可拖动和缩放背景图' : '背景图位置已锁定' }}</div>
          </div>
          
          <!-- 透明度设置滑块 -->
          <div class="opacity-slider">
            <div class="slider-label">背景图透明度:</div>
            <el-slider
              v-model="opacityValue"
              :min="10"
              :max="90"
              :step="5"
              :format-tooltip="formatOpacity"
              @change="handleOpacityChange"
            ></el-slider>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { ElMessage } from 'element-plus';

const props = defineProps({
  hasBackground: {
    type: Boolean,
    default: false
  },
  networkImageUrl: {
    type: String,
    default: ''
  },
  opacity: {
    type: Number,
    default: 40
  },
  editMode: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits([
  'add-network-image', 
  'add-local-image', 
  'remove-background', 
  'update-opacity',
  'toggle-edit-mode'
]);

const uploadType = ref('network');
const localNetworkUrl = ref('');
const opacityValue = ref(props.opacity);
const editModeActive = ref(props.editMode);

// 监听外部传入的URL变化
watch(() => props.networkImageUrl, (newUrl) => {
  if (newUrl && newUrl !== localNetworkUrl.value) {
    console.log('ImageUploader: 接收到外部网络图片URL:', newUrl);
    localNetworkUrl.value = newUrl;
  }
}, { immediate: true });

// 监听外部传入的透明度变化
watch(() => props.opacity, (newValue) => {
  if (newValue !== opacityValue.value) {
    opacityValue.value = newValue;
  }
}, { immediate: true });

// 监听外部传入的编辑模式变化
watch(() => props.editMode, (newValue) => {
  if (newValue !== editModeActive.value) {
    editModeActive.value = newValue;
  }
}, { immediate: true });

// 处理网络图片
const handleNetworkImage = () => {
  console.log('ImageUploader: 处理网络图片按钮点击');
  
  if (!localNetworkUrl.value) {
    ElMessage.error('请输入有效的网络图片URL');
    return;
  }
  
  if (!validateImageUrl(localNetworkUrl.value)) {
    ElMessage.error('请输入有效的图片URL格式（jpg、png、gif等）');
    return;
  }
  
  console.log('ImageUploader: 发送网络图片URL:', localNetworkUrl.value);
  emit('add-network-image', localNetworkUrl.value);
};

// 处理本地图片上传
const handleFileChange = (fileInfo) => {
  console.log('ImageUploader: 文件选择变更, 接收到的fileInfo:', fileInfo);
  
  if (!fileInfo || props.hasBackground) {
    console.log('ImageUploader: 未选择文件或已有背景');
    return;
  }
  
  const file = fileInfo.raw;
  if (!file) {
    console.log('ImageUploader: 未能获取raw文件对象');
    return;
  }
  
  console.log('ImageUploader: 处理的实际文件:', file.name, file.type);
  
  // 验证文件
  if (!validateFileType(file)) {
    ElMessage.error('只能上传图片文件!');
    return;
  }
  
  if (!validateFileSize(file)) {
    ElMessage.error('图片大小不能超过10MB!');
    return;
  }
  
  console.log('ImageUploader: 文件验证通过，发送上传事件，文件对象:', file.name);
  
  // 确保传递到父组件的正确事件
  emit('add-local-image', file);
};

// 格式化透明度显示
const formatOpacity = (val) => {
  return `${val}%`;
};

// 处理透明度变化
const handleOpacityChange = (value) => {
  console.log('ImageUploader: 透明度变更为:', value);
  // 将百分比转换为0-1的小数
  const opacityDecimal = value / 100;
  emit('update-opacity', opacityDecimal);
};

// 切换编辑模式
const toggleEditMode = (value) => {
  console.log('ImageUploader: 切换编辑模式为:', value);
  emit('toggle-edit-mode', value);
};

// 验证文件类型
const validateFileType = (file) => {
  return file && file.type && file.type.startsWith('image/');
};

// 验证文件大小
const validateFileSize = (file) => {
  return file && file.size / 1024 / 1024 < 10; // 10MB限制
};

// 验证上传文件是否为图片类型 - 这个函数保留但不直接使用
const validateImage = (file) => {
  console.log('ImageUploader: 验证图片文件:', file?.name);
  
  // 检查文件类型
  const isImage = validateFileType(file);
  if (!isImage) {
    return false;
  }
  
  // 检查文件大小
  const isLt10M = validateFileSize(file);
  if (!isLt10M) {
    return false;
  }
  
  return true;
};

// 验证网络图片URL
const validateImageUrl = (url) => {
  console.log('ImageUploader: 验证网络图片URL:', url);
  
  // 基本URL格式验证
  if (!url) return false;
  
  // 检查文件扩展名是否为常见图片格式
  const validExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'];
  const hasValidExtension = validExtensions.some(ext => 
    url.toLowerCase().endsWith(ext) || url.toLowerCase().includes(ext + '?')
  );
  
  // 也可以接受没有明确扩展名但URL格式看起来像图片资源的情况
  const looksLikeImageUrl = /\.(jpg|jpeg|png|gif|webp|bmp)($|\?)/i.test(url) || 
                          /\/(image|img|photo)/i.test(url);
  
  const isValid = hasValidExtension || looksLikeImageUrl;
  console.log('ImageUploader: URL验证结果:', isValid);
  return isValid;
};

// 删除背景图
const removeBackground = (e) => {
  console.log('ImageUploader: 删除背景图按钮点击');
  
  // 阻止事件冒泡到upload组件
  if (e) e.stopPropagation();
  
  emit('remove-background');
  localNetworkUrl.value = '';
};
</script>

<style lang="scss" scoped>
@use '../styles/property-panel.scss';

/* 增加样式，确保上传按钮和提示的可点击区域正确 */
.uploader-container {
  width: 100%;
  margin-bottom: 10px;
  
  .el-upload {
    width: 100%;
    display: block;
  }
  
  .upload-trigger {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }
}

.upload-tip {
  color: #999;
  font-size: 12px;
  text-align: center;
  margin-top: 8px;
}

.radio-group {
  margin-bottom: 15px;
}

.button-group {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

/* 背景图片控制样式 */
.background-controls {
  margin-top: 15px;
  padding-top: 10px;
  border-top: 1px dashed #eee;
}

/* 编辑模式切换样式 */
.edit-mode-toggle {
  margin-bottom: 15px;
  
  .mode-tip {
    margin-top: 5px;
    font-size: 12px;
    color: #909399;
  }
}

/* 透明度滑块样式 */
.opacity-slider {
  margin-top: 10px;
}

.slider-label {
  font-size: 13px;
  color: #666;
  margin-bottom: 5px;
}
</style> 